understanding list[i-1] vs list[i]-1

Posted by user3720527 on Stack Overflow See other posts from Stack Overflow or by user3720527
Published on 2014-06-08T21:11:38Z Indexed on 2014/06/08 21:24 UTC
Read the original article Hit count: 258

Filed under:
|
|
|
|

Hopefully this is a simple answer that I am just failing to understand. Full code is

public static void mystery(int[] list) {
       for( int i = list.length - 1; i>1; i --) {
           if (list[i] > list[i - 1]) {
               list[i -1] = list[i] - 2;
               list[i]++;
            }
    }
}
}

and lets say we are using a list of [2,3,4].

I know that it will output 2,2,5 but I am unclear how to actually work through it. I understand that the list.length is 3 here, and I understand that the for loop will only run once, but I am very unclear what happens at the list[i - 1] = list[i] - 2; area. Should it be list[2-1] = list[2] - 2? How does the two being outside the bracket effect it differently?

Much thanks.

© Stack Overflow or respective owner

Related posts about java

Related posts about arrays